package com.dmcb.trade.business.services;

import com.dmcb.common.business.services.BaseService;
import com.dmcb.common.business.utils.DateUtil;
import com.dmcb.common.business.utils.JedisHelper;
import com.dmcb.common.business.utils.RedisUtils;
import com.dmcb.common.web.conversion.JsonResult;
import com.dmcb.common.business.utils.WebClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by 黑米 on 2017/4/12.
 */
@Service
public class WeChatCheckService extends BaseService {
    Logger logger = LoggerFactory.getLogger(WeChatCheckService.class);

    @Autowired
    private WebClientUtil webClientUtil;

    /**
     * @param keyWord 关键词
     * @param src     链接
     * @param type    判断类型
     * @return 返回判断结果，失败则为失败，成功返回值1表示不侵权，成功返回值0表示侵权
     * @throws InterruptedException
     */
    public JsonResult check(String keyWord, String src, Integer type) throws InterruptedException {
        keyWord = keyWord.replace("，", ",").trim();
        String[] keyWords = keyWord.split(",");
        Document doc = getDoc(src);
        if (doc == null) {
            logger.error("ip被封，呼叫技术");
            return error("ip被封，呼叫技术");
        }
        Elements elements = doc.select("body");
        if (src.contains("weixin.qq.com")) {
            elements = doc.select("div#img-content");
            if (elements == null || elements.size() == 0) {
                return success(1);
            }
        }
        if (elements == null || elements.size() == 0) {
            return success(0);
        }
        String content = elements.first().text();
        if (StringUtils.isBlank(content)) {
            return success(0);
        }
        //关键词循环，1：只要含有一个即为不侵权，2：只要有一个不是即为不侵权
        for (String key : keyWords) {
            if (type == 1) {
                if (content.contains(key)) {
                    return success(1);
                }
            } else {
                if (!content.contains(key)) {
                    return success(0);
                }
            }
        }
        //循环结束，如果都不满足，
        if (type == 1) {
            return success(0);
        }
        return success(1);
    }

    public Document getDoc(String link) throws InterruptedException {
        Document doc = null;
        int times = 0;
        while (doc == null) {
            WebClientUtil.wc2 = webClientUtil.initWc(true, false, true);
            doc = webClientUtil.getDoc(link);
            if (doc == null) {
                if (times > 2) {
                    break;
                }
                JedisHelper.setIp(WebClientUtil.PROXY_REGION, "");
                DateUtil.sleep(10);
            }
            times++;
        }
        return doc;
    }


    /**
     * 获取微信文章内容文章内容进行处理，
     *
     * @param docArticle 文章内容
     * @param link       文章链接
     * @return 处理结果
     */
    public JsonResult getDoc(Document docArticle, String link) {
        String text;
        int num = 0;
        String src;
        while (true) {
            if (docArticle != null) {
                if (docArticle.select("video.vjs-tech").size() != 0) {
                    logger.info("纯视频链接" + link);
                    return warn(null, "纯视频链接，没有文字");
                }

                text = docArticle.select("body").text();
                if (StringUtils.isBlank(text)) {
                    src = webClientUtil.getPage(link).getUrl().toString();
                    if (src.startsWith("https://mp.weixin.qq.com/safe/")) {
                        logger.info("会有重定向链接，跳过：" + link);
                        return warn(null, "有重定向链接，请确认链接");
                    }
                }
                if (docArticle.text().contains("该公众号已迁移") && docArticle.text().contains("公众号迁移说明")) {
                    if (text.contains("该链接已不可访问")) {
                        return warn(null, "该链接已迁移，请核实文章链接");
                    }
                    //此处单独实例化，需要开启JS
                    WebClientUtil.wc = webClientUtil.initWc(true, false, true);
                    docArticle = webClientUtil.getDoc(link);
                    link = docArticle.select("p.weui-btn-area>a").attr("href");
                    //重新获取文章内容
                    docArticle = webClientUtil.getDoc(link);
                    if (docArticle == null) {
                        System.out.println("问题文章链接：" + link);
                        return error("");
                    }
                }
                if (StringUtils.isBlank(text) || text.contains("访问过于频繁") || text.contains("请在客户端打开") || (docArticle.select("div.qrcheck_msg") != null && docArticle.select("div.qrcheck_msg").text().contains("访问过于频繁"))) {
                    logger.error("请在客户端打开或访问频繁问题，更换IP，等待25秒后访问下一篇微信文章");
                } else
                    break;
            }
            RedisUtils.changeIP(5);
            WebClientUtil.wc = webClientUtil.initWc(false, false, true);
            docArticle = webClientUtil.getDoc(link);
            if (++num > 3) {
                return error("系统已尝试解析三次，请稍后重试");
            }
        }

        //返回值不为null，则包含错误信息
        if (getElement(docArticle) != null) {
            logger.info("该文章跳过处理：" + link);
            return warn(null, "");
        }
        //获取文章内容
        //获取文章内容
        Element elementsArticle = docArticle.select("div.rich_media_content").first();
        elementsArticle = elementsArticle == null ? docArticle.select("div#page-content").first() : elementsArticle;
        elementsArticle = elementsArticle == null ? docArticle.select("div.rich_media_content").first() : elementsArticle;
        if (elementsArticle == null) {
            //不实信息
            if (docArticle.select("div.page_rumor").first() != null) {
                logger.info("该文章跳过处理：" + link);
                return warn(null, "");
            }
            //阅读全文
            Element elementsArticle1 = docArticle.select("a#js_share_source").first();
            if (elementsArticle1 == null) {
                System.out.println("问题文章链接：" + link);
                return error("问题文章链接：" + link);
            }
            docArticle = webClientUtil.getDoc(elementsArticle1.attr("href"));
            elementsArticle = docArticle.select("div.rich_media_content").first();
            if (elementsArticle == null) {
                return warn(null, "");
            }
        }
        return success(docArticle);
    }


    /**
     * 根据已知错误样式，判断是否符合，
     *
     * @param document 文章内容
     * @return 查询结果
     */
    public Element getElement(Document document) {
        String[] styles = new String[]{"div.page_msg", "div.text-area", "h2.weui-msg__title", "div.video_card_context"};
        Element element;
        for (String style : styles) {
            element = document.select(style).first();
            if (element != null) {
                return element;
            }
        }
        return null;
    }

}
